<?php

/*
 * This will be the view page of a department depending on the passed parameter. 
 * 
 * Created by: Peter Agno Jr.
 * Date created: November 22, 2011
 * 
 * In parameters: departmentId
 */

//********************************************************************************************************
/*
 * Define the functions in here
 */

    // Start - Check if department has no ongoing route
    function noOngoingRoute($deptId) {
        $query = 
        "
            SELECT *
            FROM

                -- You now have departments that have ongoing route
                (SELECT DP.departmentId as departmentId
                FROM RouteStep as RS, RouteStep_Dept_Pos as RSDP, Department_Position as DP,

                    -- You now have filtered the ongoing routes
                    (SELECT RS.routeId as routeId
                    FROM RouteStep as RS, 

                        -- Filter routesteps
                        (SELECT stepId
                        FROM Log
                        GROUP BY stepId) as OngoingSteps

                    WHERE OngoingSteps.stepId = RS.stepId
                    GROUP BY RS.routeId) as OngoingRoutes

                WHERE OngoingRoutes.routeId = RS.routeId AND RS.stepId = RSDP.stepId AND RSDP.deptPosId = DP.deptPosId
                GROUP BY DP.departmentId) as OngoingDepts
            
            WHERE departmentId = '$deptId'
        ";
        
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        
        if ( mysql_fetch_array($result) == 0 ) {
            return true;
        }
        else {
            return false;
        }
    } // End - Check if department has an ongoing route
    
    // Start - Check if department has no data in Department_Position
    function noDeptPos($deptId) {
        $query = 
        "
            SELECT * 
            FROM Department_Position 
            WHERE departmentId = '$deptId'
        ";
        
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        
        if ( mysql_fetch_array($result) == 0 ) {
            return true;
        }
        else {
            return false;
        }
    } // End - Check if department has data in Department_Position
    
    // Start - Check if department has connection with any user
    function noConnectedUsers($deptId) {
        $query = 
        "
            SELECT *
            FROM
            
                -- You now have the departments that has connection with users
                (SELECT DP.departmentId as departmentId
                FROM Log as L, Account as A, Account_Dept_Pos as ADP, Department_Position as DP
                WHERE L.userId = A.userId AND A.userId = ADP.userId AND ADP.deptPosId = DP.deptPosId 
                GROUP BY DP.departmentId) as ConnectUsrs
            
            WHERE departmentId = '$deptId'
        ";
        
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        
        if ( mysql_fetch_array($result) == 0 ) {
            return true;
        }
        else {
            return false;
        }
    } // End - Check if department has connection with any user
    
//********************************************************************************************************

// Start - Checker for those users who will just go to the page by typing directly in the url.
if ($_POST) { 
    include("siteTop.php"); 
    include('includes/siteConfig.php'); 

    // connect to database
    $connect = mysql_connect($hostName,$rootName,$dBasePassword) or die ('Unable to connect!');
    mysql_select_db($dBaseName) or die ('Unable to select database!');
    
    $deptId = $_POST['departmentId'];
?>

<!-- HEADER START -->
    <!--JAVASCRIPT SOURCES-->
    <script src="js/jquery-1.6.2.min.js"></script>
    
    <!--ACTUAL JS SCRIPTS AND JQUERIES-->
    <script type="text/javascript">
        jQuery(document).ready(function(){ 
            // CHANGE FIRST THE CSS OF THE NAV BAR
            jQuery("#adminTools-nav").addClass("highlightMenuBar");
            jQuery("#orgSetup-nav").addClass("highlightMenuBar");
            
            // Start - Go back to admDepartmentSetup.php
            jQuery('#admDeptStpBtn').live("click",function() {
                window.location = 'admDepartmentSetup.php';
            }); // End - Go back to admDepartmentSetup.php
            
            // Start - Delete the department
            jQuery('#delDeptBtn').live("click",function() {
                var contDelete = confirm("Do you really want to delete " + jQuery("#deptName").val() + " department?");
                
                if ( contDelete == true ) {
                    // Start - Ajax for deleting the department
                    jQuery.ajax({
                        type : 'POST',
                        url : 'ajaxRequests/admDeleteDept.php',
                        dataType : 'json',
                        async : false,
                        data: {
                            deptId : jQuery("#deptId").val(),
                            deptName : jQuery("#deptName").val()
                        },
                        success : function(data){
                            // If, successful deletion of department
                            if (data) {
                                if ( data[0].flag == "success" ) {
                                    jQuery("#deptSuccessMessage").val(data[0].msg);
                                    jQuery("#deptStpMsgForm").submit();
                                }
                                else {
                                    alert(data[0].msg);
                                }
                            } // End if, successful deletion of department
                        },
                        error : function() {
                            alert("Error : Deleting the department was not successful.");
                        }
                    }); // End - Ajax for deleting the department
                } // End if for confirmation of deletion
            }); // End - Delete the department
            
            // Start - Edit the department
            jQuery('#editDeptBtn').live("click",function() {
                jQuery("#editDeptForm").submit();
            }); // End - Edit the department
            
        }); // End - jQuery document ready
    </script>
<!-- HEAD END -->

<div id="content">
<h1>View Department</h1>
    <div class="contentbox">       
        <?php
        // Check permission
        $thePermissions = array('DEPTSTP');
        if ( checkPermission( $thePermissions, $userId ) == true ) {
        ?>
            <span class="screenlet" >Department Information</span>
            <table>
                <tr>
                    <td>Department ID : </td>
                    <td>
                        <input type="hidden" name="deptId" id="deptId" value="<?php echo $deptId; ?>"/>
                        <?php echo $deptId; ?>
                    </td>
                </tr>
                <tr>
                    <td>Department Name : </td>
                    <td>
                    <?php 
                        // Get the department name
                        $query =
                            "
                                SELECT departmentName
                                FROM Department
                                WHERE departmentId = '$deptId'
                            ";
                        
                        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
                        $row = mysql_fetch_array($result);
                        
                        echo "<input type='hidden' name='deptName' id='deptName' value='".$row['departmentName']."'/>";
                        echo $row['departmentName'];
                    ?>
                    </td>
                </tr>
            </table>
        <?php
            if ( noOngoingRoute($deptId) == true && noDeptPos($deptId) == true && noConnectedUsers($deptId) == true ) {
                // Show Edit and Delete button if the department has:
                // - No ongoing route, meaning no current route is using this department
                // - no data yet in Department_Position table
                // - and no department connected with any users
                ?>
                    <input type="Submit" name="editDeptBtn" id="editDeptBtn" value="Edit" class="siteGreenButton" />
                    <input type="Submit" name="delDeptBtn" id="delDeptBtn" value="Delete" class="siteRedButton" />
                <?php
            }
        ?>
                <input type="Submit" name="admDeptStpBtn" id="admDeptStpBtn" value="Back" class="siteGreenButton" />
            <?php
            mysql_free_result($result);
        ?>
        <?php
        }
        else {
            echo "<div class='noPermissionMsgBox noPermissionMsg' style='border: 2px solid red'><div id='noPermissionMsgs'>You have no permission to view this page.</div></div>";
        }
        // End checking permission
        ?>
    </div> <!-- contentbox end div -->
    
    <!-- Hidden form to be used when the deletion of department was successful -->
    <form id="deptStpMsgForm" name="deptStpMsgForm" action="admDepartmentSetup.php" method="POST">
        <input type="hidden" name="deptSuccessMessage" id="deptSuccessMessage" value=""/>
    </form>
    
    <!-- Hidden form to be used when the edit of department was successful -->
    <form id="editDeptForm" name="editDeptForm" action="admEditDept.php" method="POST">
        <input type="hidden" name="deptId" id="deptId" value="<?php echo $deptId; ?>"/>
    </form>
    
    <div style="position:relative; visibility: hidden">end</div>    <!-- extra space for contentbox -->
</div> <!-- content end div -->

<?php
    include ("siteBottom.php"); 
}   // End - Checker for those users who will just go to the page by typing directly in the url.
else {
 echo "You are not authorized to view this page. This incident will be reported immediately.";
}
?>

